/**
*  页面通知
* 调用列表和本地存储比对  看是否有，有则不弹出，否则弹出。
* 显示一次  的拿列表的过期时间。
*   每日一次的用当天的时间作为过期时间。
*/
import { ref, onBeforeMount, onUnmounted } from "vue";

export function useNotice(apiFn, cb) {
    const noticeList = ref([]) // 当前通知列表

    // 请求通知列表
    async function getNoticeList(noticePage) {
        const res = await apiFn({ noticePage })
        noticeList.value = res.data.list || []
        checkoutNotice()
    }

    // 消息跟本地存储做比对,有则不存，不提示，否则存储加提示。// 一个页面只会有一条消息,
    function checkoutNotice() {
        if (!noticeList.value.length) {
            return
        }
        // frequency 频率 
        const currentKey = `notice-` + noticeList.value[0].id
        const frequency = noticeList.value[0].frequency
        let expirationDate = ''
        if (frequency == 'once') {
            expirationDate = new Date(noticeList.value[0].end_time).getTime()
        } else if (frequency == 'daily-once') {
            const todayYear = (new Date()).getFullYear();
            const todayMonth = (new Date()).getMonth();
            const todayDay = (new Date()).getDate();
            expirationDate = (new Date(todayYear, todayMonth, todayDay, '23', '59', '59')).getTime(); //毫秒
        }

        const currentValue = localStorage.getItem(currentKey)

        // 判断是否弹出消息 
        if (!currentValue) {
            localStorage.setItem(currentKey, expirationDate)
            cb(noticeList.value[0])
        } else {
            // 先清理过期时间戳的消息
            const currentTimestamp = new Date().getTime()

            const noticeTimestamp = localStorage.getItem(currentKey)
            if (Number(currentTimestamp) > Number(noticeTimestamp)) {
                localStorage.removeItem(currentKey)
                localStorage.setItem(currentKey, expirationDate)
                cb(noticeList.value[0])
            }

        }
    }


    return {
        getNoticeList
    };
}